package util

import (
	"github.com/golang-jwt/jwt/v5"
	"time"
)

var jwtSecret = []byte("niann_da_shuai_ge")

type Claims struct {
	UserId string `json:"userId"`
	jwt.RegisteredClaims
}

// 生成 JWT
func GenerateJWT(username string) (string, error) {
	claims := Claims{
		UserId: username,
		RegisteredClaims: jwt.RegisteredClaims{
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(24 * time.Hour * 7)), // 过期时间
			IssuedAt:  jwt.NewNumericDate(time.Now()),
		},
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	return token.SignedString(jwtSecret)
}

// 解析 JWT
func ParseJWT(tokenString string) (*Claims, error) {
	token, err := jwt.ParseWithClaims(tokenString, &Claims{}, func(token *jwt.Token) (interface{}, error) {
		return jwtSecret, nil
	})
	if err != nil {
		return nil, err
	}

	if claims, ok := token.Claims.(*Claims); ok && token.Valid {
		return claims, nil
	}
	return nil, err
}
